if not Links or not BagnonDB then return end

local currentPlayer = UnitName('player')
local itemInfo = {}
local SILVER = '|cffc7c7cf%s|r'
local TEAL = '|cff00ff9a%s|r'
local BAGNON_NUM_BAGS = 'Bags: %d'
local BAGNON_NUM_BANK = 'Bank: %d'
local BAGNON_EQUIPPED = 'Equipped'

local function CountsToInfoString(invCount, bankCount, equipCount)
	local info
	local total = invCount + bankCount + equipCount

	if invCount > 0 then
		info = BAGNON_NUM_BAGS:format(invCount)
	end

	if bankCount > 0 then
		local count = BAGNON_NUM_BANK:format(bankCount)
		info = info and strjoin(', ', info, count) or count
	end

	if equipCount > 0 then
		info = info and strjoin(', ', info, BAGNON_EQUIPPED) or BAGNON_EQUIPPED
	end

	if info then
		if total and total ~= invCount and total ~= bankCount and total ~= equipCount then
			--split into two steps for debugging purposes
			return format(TEAL, total) .. format(SILVER, format(' (%s)', info))
		end
		return format(TEAL, info)
	end
end

local function GetItemCounts(link, player)
	local invCount = BagnonDB:GetItemCount(link, KEYRING_CONTAINER, player)
	for bag = 0, NUM_BAG_SLOTS do
		invCount = invCount + BagnonDB:GetItemCount(link, bag, player)
	end

	local bankCount = BagnonDB:GetItemCount(link, BANK_CONTAINER, player)
	for i = 1, NUM_BANKBAGSLOTS do
		bankCount = bankCount + BagnonDB:GetItemCount(link, NUM_BAG_SLOTS + i, player)
	end

	local equipCount = BagnonDB:GetItemCount(link, 'e', player)
	
	return CountsToInfoString(invCount or 0, bankCount or 0, equipCount or 0) or ''
end

--make up the self populating table
local mt_index = function(self, link)
	local counts = GetItemCounts(link, getmetatable(self).player)
	self[link] = counts
	return counts
end

for player in BagnonDB:GetPlayers() do
	if player ~= currentPlayer then
		itemInfo[player] = setmetatable({}, {__index = mt_index, player = player})
	end
end

local function AddOwners(frame, link)
	for player in BagnonDB:GetPlayers() do
		local infoString
		if player == currentPlayer then
			infoString = GetItemCounts(link, player)
		else
			infoString = itemInfo[player][link]
		end

		if infoString and infoString ~= '' then
			frame:AddDoubleLine(format(TEAL, player), infoString)
		end
	end
	frame:Show()
end

function Links:BagnonDBHook(frame)
	local SetItem = frame:GetScript('OnTooltipSetItem')
	frame:SetScript('OnTooltipSetItem', function(self, ...)
		if SetItem then
			SetItem(self, ...)
		end

		local itemLink = select(2, self:GetItem())
		if itemLink and GetItemInfo(itemLink) then
			AddOwners(self, itemLink)
		end
	end)
end
if not Bagnon_Tooltip then
	Links:BagnonDBHook(GameTooltip)
	Links:BagnonDBHook(ItemRefTooltip)
end
--~ Links:RegisterHookFrame("Bagnon_Forever", nil, function (_, f) Links:BagnonDBHook(f) end)
